package com.lebang.service.earn;

import com.lebang.component.RedisClient;
import com.lebang.domain.DownMemberCountConfig;
import com.lebang.example.DownMemberCountConfigExample;
import com.lebang.mapper.DownMemberCountConfigMapper;
import com.lebang.mapper.LbbMemberMapper;
import com.lebang.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Optional;

/**
 * 新老用户每日必赚次数配置
 *
 * @Author hwq
 * @Date 2020-04-20
 */
@Service
public class DownMemberCountConfigService extends BaseService<DownMemberCountConfig, Integer, DownMemberCountConfigExample> {
    @Autowired
    private LbbMemberMapper lbbMemberMapper;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private DownMemberCountConfigMapper downMemberCountConfigMapper;
    private static final String BASE_KEY = "DownMemberCountConfig";

    /**
     * 查询用户今天可以做几次 0 代表没有找到对应的配置。
     * @param memberId 用户id
     * @return
     */
    public int checkCountByMemberId( String memberId) {
        long i = lbbMemberMapper.selectCreaTimeByMemberId(memberId).toLocalDate().until(LocalDate.now(), ChronoUnit.DAYS) + 1;
        Optional<String> wall = redisClient.Optionalhget(BASE_KEY, String.valueOf(i));
        int countMax=downMemberCountConfigMapper.selectMaxCount();
        return wall.map(Integer::parseInt).orElse(countMax);
    }

    public void  init(){
        DownMemberCountConfigExample example=new DownMemberCountConfigExample();
        redisClient.del(BASE_KEY);
        List<DownMemberCountConfig> countConfigs=this.selectByExample(example);
        countConfigs.forEach(s-> redisClient.hset(BASE_KEY,s.getDayCount().toString(),s.getWallCount().toString()));
        int countMax=downMemberCountConfigMapper.selectMaxCount();
        redisClient.set(BASE_KEY+":MAX", String.valueOf(countMax));
    }
}
